package com.foreknow.controller;

import com.foreknow.bean.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 创建一个LoginServlet来处理Login.html发送的请求
 */
public class LoginServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //在doPost中处理表单的数据
    //设置服务器端向客户端响应的内容的类型(MIME)
//    resp.setContentType("text/html;charset=utf-8");
    //设置客户端向服务器端请求的字符编码集为utf-8
//    req.setCharacterEncoding("utf-8");
    //获取到Session
    HttpSession session = req.getSession();
    PrintWriter out = resp.getWriter();
    //如何才能获取到请求的参数 req.getParameter(String s)
    String username = req.getParameter("email");
    String password = req.getParameter("password");
    //需要调用Model(Service和Dao)
    AdminService service = new AdminServiceImpl();
    Admin admin = service.isValidate(username,password);
    if(admin!=null){
//      session数据保存
      session.setAttribute("username",admin.getUsername());

      //跳转资源(转发)
//      req.getRequestDispatcher("/user/manager?q=list").forward(req,resp);

      //      //重定向
      resp.sendRedirect(req.getContextPath()+"/user/manager?q=list");

    }else {
      out.println("登录失败......");
    }
  }
}
